package com.xfc.web.controller.school;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfc.message.NoticeMessage;
import com.xfc.school.domain.*;
import com.xfc.school.service.*;
import com.xfc.wx.domain.ScWxUser;
import com.xfc.wx.service.IScWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xfc.common.annotation.Log;
import com.xfc.common.core.controller.BaseController;
import com.xfc.common.core.domain.AjaxResult;
import com.xfc.common.enums.BusinessType;
import com.xfc.common.utils.poi.ExcelUtil;
import com.xfc.common.core.page.TableDataInfo;

/**
 * 课堂评价Controller
 * 
 * @author xfc
 * @date 2022-01-02
 */
@Api(value = "course", tags = "课堂评价管理接口")
@RestController
@RequestMapping("/school/form")
public class ScClassEvaluationFormController extends BaseController
{
    @Autowired
    private IScClassEvaluationFormService scClassEvaluationFormService;

    @Autowired
    private IScCourseService scCourseService;

    @Autowired
    private IScMarketingCourseService scMarketingCourseService;

    @Autowired
    private IScTeacherService scTeacherService;

    @Autowired
    private NoticeMessage message;
    @Autowired
    private IScWxUserService wxUserService;
    @Autowired
    private IScCourseService courseService;
    @Autowired
    private IScStudentService studentService;
    @Autowired
    private IScBuyCourseService scBuyCourseService;
    @Autowired
    private IScTeacherService teacherService;
    @Autowired
    private IScCourseListService courseListService;

    /**
     * 根据用户id查询课堂评价列表
     */
    @ApiOperation("根据用户id查询课堂评价列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="studentNumber",value="学生id",dataTypeClass = String.class),
    })
    @GetMapping("/list/{id}")
    public TableDataInfo list(@PathVariable String id)
    {
        startPage();
        List<ScMarketingCourse> list = scMarketingCourseService.list(new QueryWrapper<ScMarketingCourse>().eq("student_id",id).orderByDesc("create_time"));
        list.forEach(l->{
            //查询课程名称
            //ScCourse scCourse=scCourseService.getById(l.getCourseId());
            if (Objects.nonNull(l.getCourseId())){
                ScCourse scClass=scCourseService.getById(l.getCourseId());
                if (Objects.nonNull(scClass)){
                    //课程名称
                    l.setCourseId(scClass.getClassName());
                }
            }
            //教师姓名
            ScTeacher teacher=scTeacherService.getById(l.getTeacherId());
            if (Objects.nonNull(teacher)){
                l.setTeacherId(teacher.getTeacherName());
            }
        });

        return getDataTable(list);
    }

    /**
     * 导出课堂评价列表
     */
    @PreAuthorize("@ss.hasPermi('school:form:export')")
    @Log(title = "课堂评价", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ScClassEvaluationForm scClassEvaluationForm)
    {
        List<ScClassEvaluationForm> list = scClassEvaluationFormService.list();
        ExcelUtil<ScClassEvaluationForm> util = new ExcelUtil<ScClassEvaluationForm>(ScClassEvaluationForm.class);
        return util.exportExcel(list, "form");
    }

    /**
     * 获取课堂评价详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(scClassEvaluationFormService.getById(id));
    }



    /**
     * 新增课堂评价
     */
    @Transactional
    @Log(title = "课堂评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScClassEvaluationForm scClassEvaluationForm)
    {
        if (Objects.isNull(scClassEvaluationForm)){
            return AjaxResult.error("没有评价信息");
        }
        //创建时间
        scClassEvaluationForm.setCreateTime(new Date());
        //更新评价
        scClassEvaluationFormService.saveOrUpdate(scClassEvaluationForm);
        //消课
        //查询课程是否已消课
        QueryWrapper<ScMarketingCourse> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("student_id",scClassEvaluationForm.getStudentNumber());
        queryWrapper.eq("course_id",scClassEvaluationForm.getCourseNumber());
        queryWrapper.eq("course_startime",scClassEvaluationForm.getStartTime());
        queryWrapper.eq("counrse_endtime",scClassEvaluationForm.getEndTime());
        ScMarketingCourse scMarketingCourse1=scMarketingCourseService.getOne(queryWrapper);
        if (Objects.nonNull(scMarketingCourse1)){
           logger.info("课程已消");
        }else {
            ScMarketingCourse scMarketingCourse=new ScMarketingCourse();
            scMarketingCourse.setCourseId(scClassEvaluationForm.getCourseNumber());
            scMarketingCourse.setCreateTime(new Date());
            scMarketingCourse.setState("0");
            scMarketingCourse.setStudentId(scClassEvaluationForm.getStudentNumber());
            scMarketingCourse.setCourseStartime(scClassEvaluationForm.getStartTime());
            scMarketingCourse.setCounrseEndtime(scClassEvaluationForm.getEndTime());
            scMarketingCourse.setXknumber(scClassEvaluationForm.getXknumber());
            //查询课程id
            //ScCourseList scCourse=courseListService.getOne(new QueryWrapper<ScCourseList>().eq("class_id",scClassEvaluationForm.getCourseNumber()));
//            if (Objects.nonNull(scCourse)) {
                scMarketingCourse.setTeacherId(scClassEvaluationForm.getTeacherId());
//            }
            scMarketingCourseService.save(scMarketingCourse);
            //发送通知
            QueryWrapper<ScBuyCourse> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("class_id",scClassEvaluationForm.getCourseNumber());
            queryWrapper2.eq("student_id",scClassEvaluationForm.getStudentNumber());
            queryWrapper2.gt("class_surplus_time",0);
            queryWrapper2.orderByDesc("create_time");
            queryWrapper2.last("limit 1");
            ScBuyCourse scBuyCourse=scBuyCourseService.getOne(queryWrapper2);
            if (Objects.nonNull(scBuyCourse)) {
                scBuyCourse.setClassSurplusTime(scBuyCourse.getClassSurplusTime()-scClassEvaluationForm.getXknumber());
                scBuyCourse.setUpdateTime(new Date());
                scBuyCourseService.updateById(scBuyCourse);
                //查询课程名称
                ScCourse course = courseService.getById(scClassEvaluationForm.getCourseNumber());
                if (Objects.nonNull(course)) {
                    //查询学生信息
                    ScStudent student = studentService.getById(scClassEvaluationForm.getStudentNumber());
                    if (Objects.nonNull(course)) {
                        //查询用户openId
                        ScWxUser wxUser = wxUserService.getOne(new QueryWrapper<ScWxUser>().eq("mobile", student.getStudentMobile()));
                        if (Objects.nonNull(wxUser)) {
                            //发送通知
                            message.courseDisappear(wxUser.getOpenId(), student.getStudentName(),scClassEvaluationForm.getStartTime(), course.getClassName(), "1", String.valueOf(scBuyCourse.getClassSurplusTime()));
                        }
                    } else {
                        logger.error("没有查询到用户课程,通知失败");
                    }
                } else {
                    logger.error("没有查询到用户openId,通知失败");
                }
            }else {
                logger.error("没有查询到购买课程,通知失败");
            }
        }
        //评价通知
        ScCourse course = courseService.getById(scClassEvaluationForm.getCourseNumber());
        if (Objects.nonNull(course)) {
            //查询学生信息
            ScStudent student = studentService.getById(scClassEvaluationForm.getStudentNumber());
            if (Objects.nonNull(course)) {
                //查询用户openId
                ScWxUser wxUser = wxUserService.getOne(new QueryWrapper<ScWxUser>().eq("mobile", student.getStudentMobile()));
                //查询老师信息
                ScTeacher teacher=teacherService.getById(scClassEvaluationForm.getEvaluator());
                if (Objects.nonNull(wxUser)) {
                    message.courseEvaluate(wxUser.getOpenId(),student.getStudentName(),course.getClassName(),teacher.getTeacherName());
                }
            } else {
                logger.error("没有查询到用户课程,通知失败");
            }
        } else {
            logger.error("没有查询到用户openId,通知失败");
        }
        return AjaxResult.success("消课成功");
    }


//    /**
//     * 新增课堂评价
//     */
//    @Log(title = "课堂评价", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody ScClassEvaluationForm scClassEvaluationForm)
//    {
//        scClassEvaluationForm.setCreateTime(new Date());
//        //消课
//        return toAjax(scClassEvaluationFormService.save(scClassEvaluationForm));
//    }


    /**
     * 修改课堂评价
     */
    @Log(title = "课堂评价", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScClassEvaluationForm scClassEvaluationForm) {

        if (Objects.nonNull(scClassEvaluationForm)){
            scClassEvaluationForm.setUpdateTime(new Date());
//            if (StringUtils.isEmpty(scClassEvaluationForm.getId())){
//                //发送通知
//                QueryWrapper<ScBuyCourse> queryWrapper=new QueryWrapper<>();
//                queryWrapper.eq("class_id",scClassEvaluationForm.getCourseNumber());
//                queryWrapper.eq("student_id",scClassEvaluationForm.getStudentNumber());
//                queryWrapper.gt("class_surplus_time",0);
//                queryWrapper.orderByDesc("create_time");
//                queryWrapper.last("limit 1");
//                ScBuyCourse scBuyCourse=scBuyCourseService.getOne(queryWrapper);
//                if (Objects.nonNull(scBuyCourse)) {
//                    scBuyCourse.setClassSurplusTime(scBuyCourse.getClassSurplusTime()-1);
//                    scBuyCourse.setUpdateTime(new Date());
//                    scBuyCourseService.updateById(scBuyCourse);
//                    //查询课程名称
//                    ScCourse course = courseService.getById(scClassEvaluationForm.getCourseNumber());
//                    if (Objects.nonNull(course)) {
//                        //查询学生信息
//                        ScStudent student = studentService.getById(scClassEvaluationForm.getStudentNumber());
//                        if (Objects.nonNull(course)) {
//                            //查询用户openId
//                            ScWxUser wxUser = wxUserService.getOne(new QueryWrapper<ScWxUser>().eq("mobile", student.getStudentMobile()));
//                            if (Objects.nonNull(wxUser)) {
//                                //发送通知
//                                message.courseDisappear(wxUser.getOpenId(), student.getStudentName(), scBuyCourse.getCourseStartime(), course.getClassName(), "1", String.valueOf(scBuyCourse.getClassSurplusTime()));
//                            }
//                        } else {
//                            logger.error("没有查询到用户课程,通知失败");
//                        }
//                    } else {
//                        logger.error("没有查询到用户openId,通知失败");
//                    }
//                }else {
//                    logger.error("没有查询到购买课程,通知失败");
//                }
//            }
            scClassEvaluationFormService.updateById(scClassEvaluationForm);
            //评价通知
            ScCourse course = courseService.getById(scClassEvaluationForm.getCourseNumber());
            if (Objects.nonNull(course)) {
                //查询学生信息
                ScStudent student = studentService.getById(scClassEvaluationForm.getStudentNumber());
                if (Objects.nonNull(course)) {
                    //查询用户openId
                    ScWxUser wxUser = wxUserService.getOne(new QueryWrapper<ScWxUser>().eq("mobile", student.getStudentMobile()));
                    //查询老师信息
                    ScTeacher teacher=teacherService.getById(scClassEvaluationForm.getEvaluator());
                    if (Objects.nonNull(wxUser)&&Objects.nonNull(teacher)) {
                        message.courseEvaluate(wxUser.getOpenId(),student.getStudentName(),course.getClassName(),teacher.getTeacherName());
                    }
                } else {
                    logger.error("没有查询到用户课程,通知失败");
                }
            } else {
                logger.error("没有查询到用户openId,通知失败");
            }
        }else {
            return AjaxResult.error("没有查询到数据参数");
        }

        return AjaxResult.success();
    }

    /**
     * 删除课堂评价
     */
    @PreAuthorize("@ss.hasPermi('school:form:remove')")
    @Log(title = "课堂评价", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids){
		List<String> list=new ArrayList<>();
    	if (ids!=null&&ids.length>0) {
            for (String id : ids) {
                list.add(id);
            }
		}
        return toAjax(scClassEvaluationFormService.removeByIds(list));
    }
}
